<%= stylesheet_link_tag 'search/_index' %>

<script type="text/javascript" charset="utf-8">
    bind_method(document, "keydown", backWithPrev('search'));

    $(function () {
        var keyboard = root.getWidgetById("keyboard");
        var input = $("#input");

        // 防抖函数
        function debounce(func, wait, immediate) {
            var timeout;
            return function () {
                var context = this,
                    args = arguments;
                var later = function () {
                    timeout = null;
                    if (!immediate) func.apply(context, args);
                };
                var callNow = immediate && !timeout;
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
                if (callNow) func.apply(context, args);
            };
        }

        var searchSong = debounce(function () {
            $.ajax({
                url: "/search/query_text?text=" + input.text(),
                dataType: "script"
            }).done(function () {
                FocusEngine.render();
            });
        }, 1000);

        keyboard.on("keydown", function (e) {
            e = e || window.event;
            var keyValue = e.which || e.keyCode;
            if (keyValue === 13) {
                var con = e.target.con;
                var dataset = con.dataset;
                switch (String(dataset.kind)) {
                    case "empty":
                        if (input.text()) {
                            input.text("");
                            searchSong();
                        }
                        break;
                    case "delete":
                        if (input.text()) {
                            input.text(input.text().slice(0, -1));
                            searchSong();
                        }
                        break;
                    case "letter":
                        input.text(input.text() + dataset.letter);
                        searchSong();
                }
            }
        });
    });
</script>

<div id="main">
  <div id="keyboard" class="keyboard" fe-role="Switch">
    <div class="keyboard-search">
      <%= image_tag("icons/white_search.png", class: "keyboard-search-magnifier") %>
      <div id="input" class="keyboard-search-input"></div>
    </div>

    <div class="keyboard-control">
      <div data-kind="empty" class="keyboard-control-empty keyboard-control-item" fe-role="Widget">清空</div>
      <div data-kind="delete" class="keyboard-control-delete keyboard-control-item" fe-role="Widget">删除</div>
    </div>

    <div class="keyboard-panel">
      <% letters.each do |letter| %>
        <div data-kind="letter" data-letter="<%= letter %>" class="keyboard-panel-item" fe-role="Widget"><%= letter %></div>
      <% end %>
    </div>
  </div>

  <div class="for_you">
    以下是为您推荐的
  </div>

  <%= render 'shared/tree', items: @songs %>
</div>
